import api from '@/utils/api'

const state = {
  login_info:{},
  user:{},
  user_status:'',
  coupons_num:0,
  wechat_callback:{}
}

const getters = {
  user: state => state.user,
  login_info: state => state.login_info,
  user_status: state => state.user_status,
  coupons_num: state => state.coupons_num,
  wechat_callback: state => state.wechat_callback,
}

const mutations = {
  loginInfo(state,data){
    state.login_info = data
  },
  userInfo(state,data){
    state.user = data
  },
  userStatus(state,data){
    state.user_status = data
  },
  COUPONS_NUM(state,data){
    state.coupons_num = data
  },
  wechatCallback(state,data){
    state.wechat_callback = data
  }
}

const actions = {
  login({commit},data){
    wx.setStorageSync('login_info',data)
    commit("loginInfo",data)
  },
  async setUser({commit,state},data){
    console.log('user_data: ', data)
    wx.setStorageSync('user_info',data)
    commit("userInfo",data)
    //获取有效优惠券的数量
    let result = await api.findCoupons({openid: state.login_info.openid, brand_id:state.login_info.brand_id, status: 'grant'})
    if (result.code == 0) {
      commit("COUPONS_NUM",result.data.length)
    }
  },
  bindUserStatus({commit},data){
    commit("userStatus",data)
  },
  setWechatCallback({commit},data){
    commit("wechatCallback",data)
  },
  refreshUser({commit,dispatch},data){
    api.getUserByOpenid({openid: state.login_info.openid}).then(res=>{
        if(res.code==0){
          state.user=res.data
          dispatch("setUser",res.data)
        }
    })
  }
}

export default{
  state,
  getters,
  mutations,
  actions
}
